package per.ethan.ssm.config;

import cn.hutool.core.util.CharsetUtil;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Ethan
 * @date 2020/04/28 10:17
 * 此类遵循Servlet3.0规范，在resources/META-INF/services文件夹中存在javax.servlet.ServletContainerInitializer文件，则在容器启动时，
 * 会自动加载实现了ServletContainerInitializer接口的onStartup方法
 */
public class WebConfig implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {
        // 加载spring web配置
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        ac.register(AppConfig.class);
        // refresh方法与@EnableWebMvc同时存在启动时报错（底层代码断言）,所以需要setServletContext
        ac.setServletContext(servletContext);
        ac.refresh();

        // 注册DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/");

        servletContext.addListener(new RequestContextListener());

        // utf-8过滤器
        FilterRegistration.Dynamic filterEncoding = servletContext.addFilter("filterEncoding", new CharacterEncodingFilter());
        Map<String, String> map = new HashMap<>(2);
        map.put("encoding", CharsetUtil.UTF_8);
        map.put("forceEncoding", "true");
        filterEncoding.setInitParameters(map);
        EnumSet<DispatcherType> dispatcherTypes = EnumSet
                .allOf(DispatcherType.class);
        dispatcherTypes.add(DispatcherType.REQUEST);
        dispatcherTypes.add(DispatcherType.FORWARD);
        filterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
    }

}
